//
//  ChatMessageView.swift
//  EasyChat
//
//  Created by it-go-0367 on 2021/12/24.
//

import UIKit

/** 自定义的消息气泡*/
class ChatMessageView: UIView {
    /** 消息内容区域*/
    let titleView : UIView = UIView.init()
    /** 消息内容*/
    let titleLabel : UILabel = UILabel.init()
    /** 那个角，没想好怎么设计直接上贝塞尔曲线*/
    let angleView : CAShapeLayer = CAShapeLayer.init()

    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    convenience init(frame : CGRect, text : String, belongSelf : Bool) {
        self.init(frame: frame)
        titleLabel.frame = CGRect.init(x: 10, y: 13, width: screenWidth-130, height: 1000)
        titleLabel.text = text
        titleLabel.textColor = UIColor.black
        titleLabel.textAlignment = .left
        titleLabel.font = UIFont.systemFont(ofSize: 16)
        titleLabel.numberOfLines = 0
        titleLabel.lineBreakMode = .byWordWrapping  //根据单词分割
        titleLabel.sizeToFit()
        self.frame.size = CGSize.init(width: titleLabel.frame.width+20+7, height: titleLabel.frame.height+26)
        self.backgroundColor = UIColor.init(red: 0.90, green: 0.91, blue: 0.96, alpha: 1)
        titleView.frame = CGRect.init(x: 7, y: 0, width: titleLabel.frame.width+20, height: self.frame.height)
        titleView.addSubview(titleLabel)
        var mainColor = UIColor.white  //默认气泡颜色是白色
        //设置突出角
        let bezierpath = UIBezierPath.init()
        //设置突出角的起点
        bezierpath.move(to: CGPoint.init(x: 7, y: 13))
        bezierpath.addQuadCurve(to: CGPoint.init(x: 0, y: 10), controlPoint: CGPoint.init(x: 3, y: 12))
        bezierpath.addQuadCurve(to: CGPoint.init(x: 7, y: 20), controlPoint: CGPoint.init(x: 3, y: 18))
        if belongSelf {
            //自己的发言titleView左侧不需要让出来角的位置
            titleView.frame = CGRect.init(x: 0, y: 0, width: titleLabel.frame.width+20, height: self.frame.height)
            //自己的气泡是蓝色的
            mainColor = UIColor.init(red: 0.12, green: 0.66, blue: 1, alpha: 1)
            //自己的发言，角是在右边的
            bezierpath.removeAllPoints()
            bezierpath.move(to: CGPoint.init(x: titleView.frame.maxX, y: 13))
            bezierpath.addQuadCurve(to: CGPoint.init(x: titleView.frame.maxX+7, y: 10), controlPoint: CGPoint.init(x: titleView.frame.maxX+4, y: 12))
            bezierpath.addQuadCurve(to: CGPoint.init(x: titleView.frame.maxX, y: 20), controlPoint: CGPoint.init(x: titleView.frame.maxX+4, y: 18))
        }
        titleView.backgroundColor = mainColor
        //设置圆角
        titleView.layer.masksToBounds = true
        titleView.layer.cornerRadius = 15
        self.addSubview(titleView)
        
        angleView.path = bezierpath.cgPath
        angleView.fillColor = mainColor.cgColor;
        angleView.lineWidth = 1
        angleView.strokeColor = mainColor.cgColor
        self.layer.addSublayer(angleView)
    }
}
